package com.fg.cloud.factory.controller.order;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringEscapeUtils;
import org.aspectj.apache.bcel.generic.ReturnaddressType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.fg.cloud.common.PageUtils;
import com.fg.cloud.common.Result;
import com.fg.cloud.common.ServiceException;
import com.fg.cloud.common.StatusCode;
import com.fg.cloud.common.construction.Tree;
import com.fg.cloud.common.finals.Agency;
import com.fg.cloud.common.quantity.ResultType;
import com.fg.cloud.common.reflection.ParamsReflect;
import com.fg.cloud.framework.controller.BaseController;
import com.fg.cloud.manager.entry.BaseEntity;
import com.fg.cloud.manager.entry.agency.vo.AgencyAreaVo;
import com.fg.cloud.manager.entry.factory.vo.FactoryUserVo;
import com.fg.cloud.manager.entry.order.OrderCheckEntity;
import com.fg.cloud.manager.entry.order.OrderDetailEntity;
import com.fg.cloud.manager.entry.order.OrderInfoEntity;
import com.fg.cloud.manager.entry.order.vo.OrderDetailEntityMorUnitVo;
import com.fg.cloud.manager.entry.order.vo.OrderDetailVo;
import com.fg.cloud.manager.entry.order.vo.OrderInfoVo;
import com.fg.cloud.manager.entry.product.vo.AgencyParmsVo;
import com.fg.cloud.manager.service.agency.AgencyAreaService;
import com.fg.cloud.manager.service.order.OrderCheckService;
import com.fg.cloud.manager.service.order.OrderDetailService;
import com.fg.cloud.manager.service.order.OrderInfoService;
import com.fg.cloud.manager.service.product.AgencyProductHomeService;

/**
 * @author ：
 * @date ： 2017年6月21日 下午5:35:50
 * @Desc ：订单controller
 */
@Controller
@RequestMapping(value = "/order")
public class OrderInfoController extends BaseController {

	@Autowired
	private OrderInfoService orderInfoService;
	@Autowired
	private OrderDetailService detailService ; 
	@Autowired
	private OrderCheckService checkService ; 
	@Autowired
	private AgencyProductHomeService agencyProductHomeService;
	@Autowired
	private AgencyAreaService agencyAreaService;
	/**
	  * Description:查询订单列表
	  * @param req
	  * @param resp
	  * @param search 搜索条件
	  * @param searchCondition
	  * @param page 当前页
	  * @param rows 每页行数
	  * @param sort 排序字段
	  * @param order 排序规则
	  * @author liushengchao
	  * @date 2017年8月29日下午6:09:56
	 */
	@RequestMapping(value="/findlist",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public void findList(HttpServletRequest req, HttpServletResponse resp,String search,
			OrderInfoVo searchCondition,Integer page, Integer rows, String sort, String order
			,String statusStr){

		try {
			String areaIdStr = searchCondition.getAreaIdStr();
			Long areaId = null ;
			String areaNumber = "" ;
			if(!StringUtils.isEmpty(areaIdStr)){
				String[] idArr = areaIdStr.split(",");
				areaId = Long.parseLong(idArr[idArr.length-1]);
				areaNumber = areaIdStr.replace(",", "_");
			}
			List<Tree> areaList = agencyAreaService.findListByUser(getCurrentFactoryUser().getFacId()	, getCurrentFactoryUser().getId());
			List<String> areaNumberList = new ArrayList<>();
			getUserArea(areaList,areaNumberList);
			System.out.println(areaNumberList);
			PageUtils<BaseEntity> pageinfo = new PageUtils<BaseEntity>(page, rows, sort, order);
			pageinfo.setFacId(getCurrentFactoryUser().getFacId());
			Map<String,Object> condition = ParamsReflect.getParamsByReflect(searchCondition);
			if(condition.get("orderDate <=") != null && !StringUtils.isEmpty(condition.get("orderDate <=").toString())){
				condition.put("orderDate <=", condition.get("orderDate <=")+" 23:59:59");
			}
			if(condition.get("orderDate >=") != null && !StringUtils.isEmpty(condition.get("orderDate >=").toString())){
				condition.put("orderDate >=", condition.get("orderDate >=")+" 00:00:00");
			}
			if(condition.get("completeTime <=") != null && !StringUtils.isEmpty(condition.get("completeTime <=").toString())){
				condition.put("completeTime <=", condition.get("completeTime <=")+" 23:59:59");
			}
			if(condition.get("completeTime >=") != null && !StringUtils.isEmpty(condition.get("completeTime >=").toString())){
				condition.put("completeTime >=", condition.get("completeTime >=")+" 00:00:00");
			}
			pageinfo.setCondition(condition);
			pageinfo.setFacId(getCurrentFactoryUser().getFacId());
			
			orderInfoService.findList(pageinfo, search,areaId,areaNumber,statusStr,areaNumberList);

			doResult(resp, true, StatusCode.FINDSUCCESS, pageinfo, "查询订单成功");
		} catch (Exception e) {
			doResult(resp, false, StatusCode.FINDERROR, null, ResultType.ERROE);
			e.printStackTrace();
		}
	}
	
	/**
	 * Description:订单新增
	 * @param req
	 * @param resp
	 * @param order 订单信息实体
	 * @author liushengchao
	 * @date  2017年8月30日下午7:25:29
	 */
	@RequestMapping(value="/insert" ,method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public void add(HttpServletRequest req, HttpServletResponse resp ,String data){
		try {
			OrderInfoEntity entity = JSON.parseObject(
					StringEscapeUtils.unescapeHtml4(data), OrderInfoEntity.class);
			Result result  = orderInfoService.addOrder(entity);
			doResult(resp, result.isSuccess(), result.getCode(), 
					result.getData(), result.getMessage());
		} catch (ServiceException e) {
			doResult(resp, false, e.getCode(), null, e.getMessage());
		} catch (Exception e) {
			doResult(resp, false, StatusCode.EXCEPTIONERROR, null, ResultType.ERROE);
			e.printStackTrace();
		}
	}
	
	/**
	 * Description:订单修改
	 * @param req
	 * @param resp
	 * @param order  订单信息
	 * @author liushengchao
	 * @date  2017年8月31日下午3:44:53
	 */
	@RequestMapping(value="/modify",method={RequestMethod.GET,RequestMethod.POST} )
	@ResponseBody
	public void modifyOrder(HttpServletRequest req,HttpServletResponse resp, String data) {
		try {
			OrderInfoEntity entity = JSON.parseObject(
					StringEscapeUtils.unescapeHtml4(data), OrderInfoEntity.class);
			Result result =  orderInfoService.modifyOrder(entity);
			doResult(resp, result.isSuccess(), result.getCode(), 
					result.getData(), result.getMessage());  
		} catch (ServiceException e) {
			doResult(resp, false, e.getCode(), null, e.getMessage());
		} catch (Exception e) {
			doResult(resp, false, StatusCode.EXCEPTIONERROR, null, ResultType.ERROE);
			e.printStackTrace();
		}
		
	}
	
	/**
	 * Description:订单流程流转（可批量）
	 * @param req
	 * @param resp
	 * @param orderId  订单ID集合
	 * @author liushengchao
	 * @date  2017年9月4日上午11:25:55
	 */
	@RequestMapping(value="/ordercheck",method={RequestMethod.GET,RequestMethod.POST} )
	public void checkOrder(HttpServletRequest req , HttpServletResponse resp,String orderIds){
		if(StringUtils.isEmpty(orderIds)){
			doResult(resp, false, StatusCode.LACKVALUE, null, "订单编号不能为空");
			return ;
		}
		String[] ids = orderIds.split(",");
		int flag = orderInfoService.checkOrder(ids);
		if(flag == 0 ){
			doResult(resp, false, StatusCode.EXCEPTIONERROR, null, "程序执行异常");
			return ;
		}
		doResult(resp, true, StatusCode.OPERATIONSUCCESS, null, "审核成功");
	}
	
	/**
	 * Description:财务审核
	 * @param req
	 * @param resp
	 * @param orderId  订单ID集合
	 * @author liushengchao
	 * @date  2017年9月4日上午11:25:55
	 */
	@RequestMapping(value="/financialaudit",method={RequestMethod.GET,RequestMethod.POST} )
	public void financialAudit(HttpServletRequest req , HttpServletResponse resp,String orderIds){
		if(StringUtils.isEmpty(orderIds)){
			doResult(resp, false, StatusCode.LACKVALUE, null, "订单编号不能为空");
			return ;
		}
		String[] ids = orderIds.split(",");
		int flag = orderInfoService.financialAudit(ids);
		if(flag == 0 ){
			doResult(resp, false, StatusCode.EXCEPTIONERROR, null, "程序执行异常");
			return ;
		}
		doResult(resp, true, StatusCode.OPERATIONSUCCESS, null, "审核成功");
	}
	
	/**
	 * Description:业务反审核（可批量）
	 * @param req
	 * @param resp
	 * @param orderId 订单ID集合
	 * @param reamrk 反审核原因
	 * @author liushengchao
	 * @date  2017年9月4日上午11:51:27
	 */
	@RequestMapping(value="/reverse",method={RequestMethod.GET,RequestMethod.POST})
	public void reverseOrder(HttpServletRequest req , HttpServletResponse resp,String orderIds,String remark){
		if(StringUtils.isEmpty(orderIds)){
			doResult(resp, false, StatusCode.LACKVALUE, null, "订单编号不能为空");
			return ;
		}
		String[] ids = orderIds.split(",");
		int flag = orderInfoService.reverseOrder(ids,remark);
		if(flag == 0 ){
			doResult(resp, false, StatusCode.EXCEPTIONERROR, null, "程序执行异常");
			return ;
		}
		doResult(resp, true, StatusCode.SAVESUCCESS, null, "反审核成功");
	}
	
	/**
	 * Description:逻辑删除订单(可批量)
	 * @param req
	 * @param resp
	 * @param orderId 订单id集合
	 * @author liushengchao
	 * @date  2017年9月4日下午3:06:28
	 */
	@RequestMapping(value="/delOrder",method={RequestMethod.GET,RequestMethod.POST})
	public void delOrder(HttpServletRequest req , HttpServletResponse resp,String orderIds){
		if(StringUtils.isEmpty(orderIds)){
			doResult(resp, false, StatusCode.LACKVALUE, null, "订单编号不能为空");
			return ;
		}
		String[] ids = orderIds.split(",");
		int flag = orderInfoService.delOrder(ids);
		if(flag == 0 ){
			doResult(resp, false, StatusCode.EXCEPTIONERROR, null, "程序执行异常");
			return ;
		}
		doResult(resp, true, StatusCode.SAVESUCCESS, null, "删除成功");
	}
	
	/**
	 * Description:查询订单详情
	 * @param req
	 * @param resp
	 * @param id 订单ID
	 * @author liushengchao
	 * @date  2017年9月5日下午3:59:50
	 */
	@RequestMapping(value="/detail",method={RequestMethod.GET,RequestMethod.POST})
	public void orderDetail(HttpServletRequest req , HttpServletResponse resp,Long id
			,String orders,String sort){
		if(id < 1){
			doResult(resp, false, StatusCode.LACKVALUE, null, "订单ID不能为空");
			return ;
		}
		OrderInfoEntity order = orderInfoService.find(id);
		if(order == null ){
			doResult(resp, false, StatusCode.NORETRUNDATA, null, "查询结果为空");
			return ;
		}
		List<OrderDetailEntity> detail = detailService.selectByOrderId(id,orders,sort);
		List<OrderCheckEntity> operatorRecord = checkService.selectByOrderId(id);
		if(detail == null || detail.size() < 0){
			doResult(resp, false, StatusCode.NORETRUNDATA, null, "该订单没有商品信息");
			return ;
		}
//		String detailStr = JSON.toJSONString(detail);
//		order.setDetails(detailStr);
		order.setListDetails(detail);
		order.setOperatorRecords(operatorRecord);
		
		doResult(resp, true, StatusCode.FINDSUCCESS, order, "查询成功");
	}
	
	
	/**
	 * Description:厂商端查询基础订单头信息
	 * @param entity
	 * @author around
	 * @date 2017年9月6日下午10:36:11
	 */
	@RequestMapping("findOrderInfo")
	@ResponseBody
	public void findOrderInfo(HttpServletResponse response, Integer page, Integer rows, 
			String sort, String order, OrderInfoEntity entity, String filterText) {
		try {
			PageUtils<OrderInfoEntity> pageinfo = 
					new PageUtils<OrderInfoEntity>(page, rows, sort, order);
			Map<String, Object> condition = pageinfo.getCondition();
			condition.put("ageId", entity.getAgeId());
			condition.put("facId", getCurrentFactoryUser().getFacId());
			condition.put("filterText", filterText);
			condition.put("orderStatus", entity.getOrderStatus());
			
			orderInfoService.findList(pageinfo);
			doResult(response, true, StatusCode.FINDSUCCESS, pageinfo, ResultType.FIND_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(response, false, StatusCode.EXCEPTIONERROR, null, ResultType.FIND_FAULT);
		}
	}
	
	/**
	 * Description:订单新增商品选择
	 * @param req
	 * @param resp
	 * @param page
	 * @param rows
	 * @param sort
	 * @param order
	 * @param param
	 * @param ageId 经销商ID
	 * @author liushengchao
	 * @date  2017年9月13日上午9:22:57
	 */
	@RequestMapping(value="/chooseproduct")
	@ResponseBody
	public void findProductForOrder(HttpServletRequest req ,HttpServletResponse resp, Integer page, Integer rows, 
			String sort, String order,AgencyParmsVo param,Long ageId){
		try {
			PageUtils<OrderDetailEntityMorUnitVo> pageinfo = new PageUtils<OrderDetailEntityMorUnitVo>(page,rows,sort,order);
			
			Map<String, Object> condition = pageinfo.getCondition();
			FactoryUserVo factory = getCurrentFactoryUser();
			condition.put("tableName", Agency.getTableName(factory.getFacId()));
			condition.put("facId", factory.getFacId());
			condition.put("ageId", ageId);
			condition.put("categoryId", param.getCategoryId());
			String categoryNumber = "" ;
			String number = param.getCategoryNumber() ;
			if("".equals(number)){
				categoryNumber = "0";
			}else{
				String numberRep = param.getCategoryNumber().replace(",", "_") ;
				categoryNumber = "0_"+numberRep ;
			}
//			categoryNumber = "".equals(param.getCategoryNumber())?"0": param.getCategoryNumber().replace(",", "_") ;
			condition.put("categoryNumber", categoryNumber);
			condition.put("productName", param.getProductName());//商品名:包含了商品编码,规则,名称
			
			agencyProductHomeService.findByCategory(pageinfo,"factory");
			doResult(resp, true, StatusCode.FINDSUCCESS, pageinfo, ResultType.FIND_SUCCESS);
		} catch (Exception e) {
			doResult(resp, false, StatusCode.FINDERROR, null, ResultType.FIND_FAULT);
			e.printStackTrace();
		}
	}
	
	/**
	 * Description:订单作废
	 * @param req
	 * @param resp
	 * @param orderIds 订单ID集合（可多选）
	 * @param orderStatus 订单状态
	 * @author liushengchao
	 * @date  2017年9月26日下午4:24:30
	 */
	@RequestMapping(value="/cancel")
	@ResponseBody
	public void cancelOrder(HttpServletRequest req , HttpServletResponse resp,String orderIds
			,String remark){
		if(StringUtils.isEmpty(orderIds)){
			doResult(resp, false, StatusCode.LACKVALUE, null, "订单编号不能为空");
			return ;
		}
		String[] ids = orderIds.split(",");
		int flag = orderInfoService.CancelOrder(ids,remark);
		if(flag == 0 ){
			doResult(resp, false, StatusCode.EXCEPTIONERROR, null, "程序执行异常");
			return ;
		}
		doResult(resp, true, StatusCode.SAVESUCCESS, null, "订单已作废");
		return ;
	}
	
	/**
	 * Description:订单修改后保存并审核
	 * @param req
	 * @param resp
	 * @param data 订单修改后数据
	 * @author liushengchao
	 * @date  2017年10月13日下午2:57:45
	 */
	@RequestMapping(value="/saveandcheck")
	@ResponseBody
	public void saveAndfinancialCheck(HttpServletRequest req,HttpServletResponse resp, String data){
		try {
			OrderInfoEntity entity = JSON.parseObject(
					StringEscapeUtils.unescapeHtml4(data), OrderInfoEntity.class);
			Result result =  orderInfoService.saveAndCheck(entity);
			doResult(resp, result.isSuccess(), result.getCode(),result.getData(), result.getMessage());  
		} catch (ServiceException e) {
			doResult(resp, false, e.getCode(), null, e.getMessage());
		} catch (Exception e) {
			doResult(resp, false, StatusCode.EXCEPTIONERROR, null, ResultType.ERROE);
			e.printStackTrace();
		}
	}
	
	
	/**
	 * Description:获取厂商用户的区域权限
	 * @param areaTreeList 区域权限树
	 * @param areaNumberList
	 * @return areaNumberList 区域权限列表
	 * @author liushengchao
	 * @date  2017年11月8日下午6:21:29
	 */
	public List<String> getUserArea(List<Tree> areaTreeList,List<String> areaNumberList){
		if(areaTreeList != null && areaTreeList.size() > 0 ){
			int flag  = 0 ;
			String pnumber = "";
			for(Tree areaTree : areaTreeList){
				String number = areaTree.getNumber()+"_"+areaTree.getId();
				if(!"0".equals(number)){
					pnumber = number.substring(0, number.lastIndexOf("_"));
				}
				if(areaTree.getChildren().isEmpty() && areaTree.isChecked()){
					areaNumberList.add(areaTree.getNumber()+"_"+areaTree.getId());
					flag = flag + 1 ;
				}
				if(areaTree.getChildren() != null ){
					getUserArea(areaTree.getChildren(),areaNumberList);
				}
			}
			if(flag == areaTreeList.size()){
				for(int i = 0 ; i < areaNumberList.size() ; i ++ ){
					String number = areaNumberList.get(i);
					if(number.contains(pnumber)){
						areaNumberList.remove(number);
						i--;
					}
				}
			    areaNumberList.add(pnumber);
			}
		}
		return areaNumberList;
	}
	
}
